package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacades "github.com/hulutech-web/http_result"
	"goravel/app/models"
	"goravel/packages/sms/contracts"
	smsfacades "goravel/packages/sms/facades"
	"math/rand"
	"strconv"
	"time"
)

type SmsController struct {
	//Dependent services
}

func NewSmsController() *SmsController {
	return &SmsController{
		//Inject services
	}
}

func (r *SmsController) ValidCode(ctx http.Context) http.Response {
	mobile := ctx.Request().Input("mobile", "")
	//检查用户是否存在
	var user models.User
	facades.Orm().Query().Where("mobile=?", mobile).First(&user)
	if user.ID == 0 {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "用户不存在", nil)
	}
	exist := facades.Cache().Has(mobile)
	if exist {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "发送过于频繁，请5分钟后再试!!", nil)
	}
	code := randomCode()
	msg := contracts.Message{
		Data:    map[string]string{"code": code},
		Content: "您的验证码是{code}，请勿泄露于他人！",
	}
	err := smsfacades.SMS().Send(mobile, msg)
	if err != nil {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, err.Error(), nil)
	}
	facades.Cache().Put(mobile, code, 5*time.Minute) // 5分钟有效
	return httpfacades.NewResult(ctx).Success("发送成功", nil)
}

// 发送注册验证码
func (r *SmsController) ValidRegCode(ctx http.Context) http.Response {
	mobile := ctx.Request().Input("mobile", "")
	//检查用户是否存在
	var user models.User
	facades.Orm().Query().Where("mobile=?", mobile).First(&user)
	if user.ID != 0 {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "用户已存在，请勿重复注册", nil)
	}
	exist := facades.Cache().Has(mobile)
	if exist {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "发送过于频繁，请5分钟后再试!!", nil)
	}
	code := randomCode()
	msg := contracts.Message{
		Data:    map[string]string{"code": code},
		Content: "您的验证码是{code}，请勿泄露于他人！",
	}
	err := smsfacades.SMS().Send(mobile, msg)
	if err != nil {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, err.Error(), nil)
	}
	facades.Cache().Put(mobile, code, 5*time.Minute) // 5分钟有效
	return httpfacades.NewResult(ctx).Success("发送成功", nil)
}

// 随机4位验证码
func randomCode() string {
	code := strconv.Itoa(rand.Intn(8999) + 1000)
	return code
}
